package com.klikmee.sms.chat.web.usecases;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;

import com.dotexe.webframework.core.ClientApplication;
import com.dotexe.webframework.core.clientactions.MessageBox;
import com.dotexe.webframework.core.datasources.CollectionDataSource;
import com.dotexe.webframework.core.datasources.ObjectDataSource;
import com.dotexe.webframework.core.triggers.Trigger;
import com.klikmee.sms.chat.web.dao.SignatureDAO;
import com.klikmee.sms.chat.web.dao.TemplateDAO;
import com.klikmee.sms.chat.web.dto.IndividualBulkReceiver;
import com.klikmee.sms.chat.web.dto.NumberPrefix;
import com.klikmee.sms.chat.web.service.SMSChatServiceImpl;
import com.klikmee.sms.chat.web.util.SpringBeansLookup;
import com.klikmee.sms.services.chat.model.BulkGroup;
import com.klikmee.sms.services.chat.model.Signature;
import com.klikmee.sms.services.chat.model.Template;

public class BulkSendForm extends ClientApplication {

	private CollectionDataSource dsSignatures;
	private ArrayList<String> bcSignatures;
	private CollectionDataSource dsTemplates;
	private ArrayList<String> bcTemplates;
	private CollectionDataSource dsNumberPrefix;
	private ArrayList<String> bcNumberPrefix;
	private ObjectDataSource dsMessage;
	private ArrayList<String> bcMessage;
	private ObjectDataSource dsBulkGroup;
	private ArrayList<String> bcBulkGroup;
	private ObjectDataSource dsBulkIndividual;
	private ArrayList<String> bcBulkIndividual;

	private Boolean groupSelection;

	private TemplateDAO templateDAO;
	private List<Template> templates;

	private SignatureDAO signatureDAO;
	private List<Signature> signatures;

	private List<NumberPrefix> listOfPrefix = new ArrayList<NumberPrefix>();

	private BulkGroupListForm bulkGroupList;

	public void load() throws Exception {
		super.load();

		this.dsSignatures = new CollectionDataSource("dsSignatures");
		this.getDataSources().add(this.dsSignatures);
		this.bcSignatures = new ArrayList<String>();
		this.bcSignatures.add("Name");
		this.bcSignatures.add("Signature");
		this.bcSignatures.add("Active");

		this.dsTemplates = new CollectionDataSource("dsTemplates");
		this.getDataSources().add(this.dsTemplates);
		this.bcTemplates = new ArrayList<String>();
		this.bcTemplates.add("Name");
		this.bcTemplates.add("Template");
		this.bcTemplates.add("Active");

		this.dsNumberPrefix = new CollectionDataSource("dsNumberPrefix");
		this.getDataSources().add(this.dsNumberPrefix);
		this.bcNumberPrefix = new ArrayList<String>();
		this.bcNumberPrefix.add("Name");

		this.dsMessage = new ObjectDataSource("dsMessage");
		this.getDataSources().add(this.dsMessage);
		this.bcMessage = new ArrayList<String>();
		this.bcMessage.add("Name");
		this.bcMessage.add("Template");
		this.bcMessage.add("Active");

		this.dsBulkGroup = new ObjectDataSource("dsBulkGroup");
		this.getDataSources().add(this.dsBulkGroup);
		this.bcBulkGroup = new ArrayList<String>();
		this.bcBulkGroup.add("GroupName");

		this.dsBulkIndividual = new ObjectDataSource("dsBulkIndividual");
		this.getDataSources().add(this.dsBulkIndividual);
		this.bcBulkIndividual = new ArrayList<String>();
		this.bcBulkIndividual.add("PhoneNumber");

		this.triggers.add(new Trigger(this, "btnSendClick"));
		this.triggers.add(new Trigger(this, "btnCancelClick"));
		this.triggers.add(new Trigger(this, "btnSelectGroupClick"));
		this.triggers.add(new Trigger(this, "cbSignatureSelectedIndexChanged"));
		this.triggers.add(new Trigger(this, "cbTemplateSelectedIndexChanged"));

	}

	@Override
	public void start() throws Exception {
		super.start();

		if (groupSelection) {
			ChangeControlVisibility("txtIndividual", false);
			ChangeControlVisibility("cbNumberPrefix", false);
			ChangeControlVisibility("txtGroup", true);
			ChangeControlVisibility("btnSelectGroup", true);
		} else {
			ChangeControlVisibility("txtIndividual", true);
			ChangeControlVisibility("cbNumberPrefix", true);
			ChangeControlVisibility("txtGroup", false);
			ChangeControlVisibility("btnSelectGroup", false);
		}

		templateDAO = SpringBeansLookup.getBean(TemplateDAO.class);
		templates = templateDAO.findAllActive();
		this.dsTemplates.setSource(templates);
		this.dsTemplates.bind(bcTemplates);

		signatureDAO = SpringBeansLookup.getBean(SignatureDAO.class);
		signatures = signatureDAO.findAllActive();
		this.dsSignatures.setSource(signatures);
		this.dsSignatures.bind(bcSignatures);

		getNumberPrefix();

		this.dsMessage.setSource(new Template());
		this.dsMessage.bind(bcMessage);

		this.dsBulkIndividual.setSource(new IndividualBulkReceiver());
		this.dsBulkIndividual.bind(bcBulkIndividual);

	}

	public void btnSendClick() throws InstantiationException, IllegalAccessException, JSONException, Exception {
		SMSChatServiceImpl smsChatServiceImpl = SpringBeansLookup.getBean(SMSChatServiceImpl.class);
		Signature signature = (Signature) this.dsSignatures.getSelectedItem();
		Template template = (Template) this.dsMessage.getSource();

		if (this.groupSelection) {
			BulkGroup group = (BulkGroup) this.dsBulkGroup.getSource();
			if (group == null) {
				MessageBox.Show(this, "Info", "Morate odabrati grupu!");
				return;
			}
			int numberOfMessagesSent = smsChatServiceImpl.sendBulkMessage(template.getTemplate(), group, signature.getSignature());
			MessageBox.Show(this, "Obavestenje", String.format("Broj poslatih poruka je %s", numberOfMessagesSent));
		} else {
			if (this.dsNumberPrefix.getSelectedItem() == null) {
				MessageBox.Show(this, "Info", "Morate odabrati prefix!");
				return;
			}

			String number = ((IndividualBulkReceiver) this.dsBulkIndividual.getSource()).getPhoneNumber();

			if (number == null) {
				MessageBox.Show(this, "Info", "Morate uneti broj telefona!");
				return;
			}

			Pattern pattern = Pattern.compile("^[0-9]{6,7}$");
			Matcher matcher = pattern.matcher(number);

			if (!matcher.find()) {
				MessageBox.Show(this, "Info", "Telefonski broj mora imati 6 ili 7 cifara!");
				return;
			}

			String numberPrefix = ((NumberPrefix) this.dsNumberPrefix.getSelectedItem()).getName();
			String fullNumber = numberPrefix + number;
			
			int sendingResult = smsChatServiceImpl.sendSingleBulk(fullNumber, template.getTemplate(), signature.getSignature());
			if (sendingResult > 0) {
				MessageBox.Show(this, "Obavestenje", String.format("Poruka je poslata na %s", number));
			} else {
				// TODO Makcro to finish this method
			}
		}
	}

	public void btnCancelClick() throws InstantiationException, IllegalAccessException, JSONException, Exception {
		this.hide();
	}

	public void btnSelectGroupClick() throws InstantiationException, IllegalAccessException, JSONException, Exception {
		bulkGroupList = createChildApplication(BulkGroupListForm.class);
		bulkGroupList.triggers.get("gvBulkGroupsCellDoubleClick").addOnFire(this, "afterBulkGroupSelected");
		this.showChildApp(bulkGroupList);
		bulkGroupList.start();
	}

	public void afterBulkGroupSelected() throws InstantiationException, IllegalAccessException, JSONException, Exception {
		BulkGroup bulkGroup = (BulkGroup) ((CollectionDataSource) (bulkGroupList.getDataSources().get("dsBulkGroups"))).getSelectedItem();

		this.dsBulkGroup.setSource(bulkGroup);
		this.dsBulkGroup.bind(bcBulkGroup);

		MessageBox.Show(this, "Obavestenje", String.format("Izabrana je %s grupa!", bulkGroup.getGroupName()));

		bulkGroupList.hide();
	}

	public void cbSignatureSelectedIndexChanged() throws InstantiationException, IllegalAccessException, JSONException, Exception {
	}

	public void cbTemplateSelectedIndexChanged() throws InstantiationException, IllegalAccessException, JSONException, Exception {
		this.dsMessage.setSource(dsTemplates.getSelectedItem());
		this.dsMessage.bind(bcMessage);
	}

	public void setGroupSelection(Boolean groupSelection) {
		this.groupSelection = groupSelection;
	}

	public Boolean getGroupSelection() {
		return groupSelection;
	}

	public void getNumberPrefix() throws SecurityException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, JSONException, NoSuchMethodException, InvocationTargetException {
		listOfPrefix.clear();
		listOfPrefix.add(new NumberPrefix("38160"));
		listOfPrefix.add(new NumberPrefix("38161"));
		listOfPrefix.add(new NumberPrefix("38162"));
		listOfPrefix.add(new NumberPrefix("38163"));
		listOfPrefix.add(new NumberPrefix("38164"));
		listOfPrefix.add(new NumberPrefix("38165"));
		listOfPrefix.add(new NumberPrefix("38169"));

		this.dsNumberPrefix.setSource(listOfPrefix);
		this.dsNumberPrefix.bind(bcNumberPrefix);
	}
}